Page({
  data: {
    scale: 1, //图片的当前缩放倍数，1表示原始大小
    minScale: 1,  //允许的最小缩放倍数，防止图片过小
    maxScale: 4,  //允许的最大缩放倍数，4倍放大
    offsetX: 0,   //图片在canvas中的水平偏移像素
    offsetY: 0,   //图片在canvas中的垂直偏移像素
    scalePercent: 100,
    canvasWidth: 0,   //当前canvas的实际宽度（像素）
    canvasHeight: 0,  //当前canvas的实际高度（像素）
    imageWidth: 0,    //加载的图片原始宽度（像素）
    imageHeight: 0,   //加载的图片原始高度（像素）
    lastTouchTime: 0, //用于检测双击事件的时间戳
    fitScale: 1,  //根据canvas尺寸自动计算的最佳初始缩放比例
    isImageLoaded: false,
    
    // 新增：防抖和节流相关
    lastMoveTime: 0,
    moveThrottleInterval: 16, // 约60fps
    lastScale: 1,
    isScaling: false,
    
    // 新增：精确位置保持
    lastCenterX: 0,
    lastCenterY: 0,
    lastImageCenterX: 0,
    lastImageCenterY: 0,
    
    // 新增：展品数据
    chapterList: [],  //篇章列表
    exhibitList: [],  //展项列表
    isLoading: true,
    loadingError: null,
    // 在Page({})的data中新增
    selectedChapter: null,
    
    isMouseDown: false,
    mouseStartX: 0,
    mouseStartY: 0,
    mouseStartOffsetX: 0,
    mouseStartOffsetY: 0,
    
    // 新增：Canvas 2D相关
    canvas: null,
    ctx: null,
    image: null,
    iconImage: null, // 添加图标图像变量
    
    // 新增：展项坐标和点击状态
    position: [],
    exhibitPositions: [], // 存储展项坐标信息
    showContentModal: false, // 是否显示内容弹窗
    currentExhibitContent: '', // 当前显示的内容
    currentExhibitName: '', // 当前显示的展项名称
    clickedExhibitId: null // 当前点击的展项ID
  },

  // 页面加载时的回调
  onLoad() {
    this.getExhibitList();
  },

  // 创建成功时的回调
  onReady() {
    this.initCanvas();
  },

  // 获取展品列表
  getExhibitList() {
    const app = getApp();
    //const apiUrl = app.globalData.baseUrl + 'exhibit_one/get_exhibit_list';
    const apiUrl = 'https://nzy-api.congqian.cn/Api/admin/exhibit_one/get_exhibit_list';
    
    wx.request({
      url: apiUrl,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const chapterList = res.data.data.one || [];
          var exhibitList = [];

          for (let i = 0; i < chapterList.length; i++) {
            //先模拟  的坐标
            if (chapterList[i].children.length != 0) {
              //把找到的第一个有子级的展项展示出来
              exhibitList = chapterList[i].children;
              // 找到就停
              break;
            }
          }

          this.setData({
            chapterList: chapterList,
            exhibitList: exhibitList,
            isLoading: false,
            loadingError: null
          });
          
          // 为展项生成坐标（示例坐标，实际使用时需要根据地图调整）
          this.generateExhibitPositions(exhibitList);
          
        } else {
          this.setData({
            exhibitList: [],
            exhibitPositions: [],
            isLoading: false,
            loadingError: res.data?.message || '获取展品列表失败'
          });
        }
      },
      fail: (error) => {
        this.setData({
          exhibitList: [],
          exhibitPositions: [],
          isLoading: false,
          loadingError: '网络请求失败，请检查网络连接'
        });
      }
    });
  },

  // 生成展项坐标（示例实现，实际使用时需要根据地图调整）
  generateExhibitPositions(exhibitList) {
    const positions = [];
    exhibitList.forEach((exhibit, index) => {
      //把展项信息添加到数组中
      positions.push({
        id: exhibit.id,
        name: exhibit.name,
        content: exhibit.content || '暂无介绍',
        x: exhibit.coordinates_x,
        y: exhibit.coordinates_y,
      });
    });

    this.setData({
      exhibitPositions: positions,
      isLoading: false,
      loadingError: null
    });
    
    // 重新绘制画布
    if (this.data.isImageLoaded) {
      this.drawImage();
    }
  },


  // 初始化Canvas 2D
  initCanvas() {
    const query = wx.createSelectorQuery().in(this);
    query.select('#mapCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        if (!res || !res[0]) return;
        
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        const { width, height } = res[0];
        
        // 设置canvas实际尺寸
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = width * dpr;
        canvas.height = height * dpr;
        ctx.scale(dpr, dpr);
        
        this.setData({
          canvas,
          ctx,
          canvasWidth: width,
          canvasHeight: height
        });
        
        this.loadImage();
      });
  },

  // 加载图片
  loadImage() {
    const { canvas, ctx, canvasWidth, canvasHeight } = this.data;

    if (!canvas || !ctx) return;

    const image = canvas.createImage();
    image.onload = () => {
      const scaleX = canvasWidth / image.width;
      const scaleY = canvasHeight / image.height;
      const fitScale = Math.min(scaleX, scaleY) * 0.9;

      // 加载图标图片
      const iconImage = canvas.createImage();
      iconImage.onload = () => {
        this.setData({
          image,
          iconImage,
          imageWidth: image.width,
          imageHeight: image.height,
          fitScale: fitScale,
          scale: fitScale,
          minScale: fitScale,
          scalePercent: Math.floor(fitScale * 100),
          isImageLoaded: true
        });

        this.drawImage();
      };
      iconImage.src = 'https://nzy.gonng.com/storage/mini/map-icon.png';
    };
    image.src = 'https://nzy.gonng.com/storage/mini/map.png';
  },

  // 绘制图片和展项名称
  drawImage() {
    if (!this.data.isImageLoaded || !this.data.ctx) return;
    
    const { ctx, canvasWidth, canvasHeight, image, scale, offsetX, offsetY, imageWidth, imageHeight, exhibitPositions } = this.data;
    
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    
    const scaledWidth = imageWidth * scale;
    const scaledHeight = imageHeight * scale;
    const x = (canvasWidth - scaledWidth) / 2 + offsetX;
    const y = (canvasHeight - scaledHeight) / 2 + offsetY;
    
    // 绘制地图图片
    ctx.drawImage(
      image,
      0, 0, imageWidth, imageHeight,
      x, y, scaledWidth, scaledHeight
    );
    
    // 绘制展项名称
    this.drawExhibitNames(x, y, scale);
  },

  // 绘制展项名称
  drawExhibitNames(mapX, mapY, scale) {
    const { ctx, exhibitPositions, iconImage } = this.data;

    if (!exhibitPositions || exhibitPositions.length === 0) return;

    // 设置字体和文本对齐方式
    ctx.font = 'bold 14px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    // 图标尺寸
    const iconSize = 24;
    const iconMargin = 8; // 图标与文字之间的间距

    exhibitPositions.forEach(exhibit => {
      // 计算展项在缩放后的实际位置
      const textX = mapX + (exhibit.x * scale);
      const textY = mapY + (exhibit.y * scale);

      // 获取文本宽度
      const textWidth = ctx.measureText(exhibit.name).width;
      const paddingX = 16; // 水平内边距
      const paddingY = 8;  // 垂直内边距

      // 标签尺寸
      const labelWidth = textWidth + paddingX * 2;
      const labelHeight = 28; // 标签高度

      // 标签位置（向上调整，为图标留出空间）
      const labelX = textX - labelWidth / 2;
      const labelY = textY - labelHeight / 2 - iconSize - iconMargin;

      // 绘制标签背景（圆角矩形）
      const cornerRadius = 6; // 圆角半径

      // 绘制阴影
      ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
      ctx.shadowBlur = 4;
      ctx.shadowOffsetX = 2;
      ctx.shadowOffsetY = 2;

      // 绘制背景圆角矩形
      ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
      this.drawRoundedRect(ctx, labelX, labelY, labelWidth, labelHeight, cornerRadius);

      // 绘制边框
      ctx.strokeStyle = '#0066CC';
      ctx.lineWidth = 1.5;
      this.drawRoundedRect(ctx, labelX, labelY, labelWidth, labelHeight, cornerRadius, true);

      // 重置阴影
      ctx.shadowColor = 'transparent';
      ctx.shadowBlur = 0;
      ctx.shadowOffsetX = 0;
      ctx.shadowOffsetY = 0;

      // 绘制文字
      ctx.fillStyle = '#0066CC';
      ctx.fillText(exhibit.name, textX, textY - iconSize - iconMargin);

      // 绘制图标（在文字下方）
      if (iconImage) {
        const iconX = textX - iconSize / 2;
        const iconY = textY - iconSize / 2;
        ctx.drawImage(iconImage, iconX, iconY, iconSize, iconSize);
      }

      // 存储点击区域（用于点击检测）- 包含文字和图标区域
      exhibit.clickArea = {
        x: Math.min(labelX, textX - iconSize / 2),
        y: Math.min(labelY, textY - iconSize / 2),
        width: Math.max(labelWidth, iconSize),
        height: labelHeight + iconSize + iconMargin
      };
    });
  },
  

  // 绘制圆角矩形
  drawRoundedRect(ctx, x, y, width, height, radius, stroke = false) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + width - radius, y);
    ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
    ctx.lineTo(x + width, y + height - radius);
    ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
    ctx.lineTo(x + radius, y + height);
    ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
    
    if (stroke) {
      ctx.stroke();
    } else {
      ctx.fill();
    }
  },

  // 优化的画布点击事件处理（删除所有重复的handleCanvasTap）
  handleCanvasTap(e) {
    console.log('点击检测开始');
    const { exhibitPositions, scale, offsetX, offsetY, imageWidth, imageHeight, canvasWidth, canvasHeight } = this.data;
    
    if (!exhibitPositions || exhibitPositions.length === 0) return;
    
    // 获取点击坐标
    const tapX = e.detail.x;
    const tapY = e.detail.y;
    
    // 计算地图在画布中的实际位置
    const scaledWidth = imageWidth * scale;
    const scaledHeight = imageHeight * scale;
    const mapX = (canvasWidth - scaledWidth) / 2 + offsetX;
    const mapY = (canvasHeight - scaledHeight) / 2 + offsetY;
    
    // 检查是否点击了某个展项标签
    let clickedExhibit = null;
    let minDistance = Infinity;
    
    // 使用更精确的点击检测 - 考虑标签的实际尺寸
    exhibitPositions.forEach(exhibit => {
      if (!exhibit || !exhibit.x || !exhibit.y) return;
      
      // 计算展项在画布中的实际位置
      const exhibitX = mapX + (exhibit.x * scale);
      const exhibitY = mapY + (exhibit.y * scale);
      
      // 重新计算标签尺寸（保持与绘制时一致）
      const ctx = this.data.ctx;
      ctx.font = 'bold 14px Arial';
      const textWidth = ctx.measureText(exhibit.name).width;
      const paddingX = 16;
      const paddingY = 8;
      const labelWidth = textWidth + paddingX * 2;
      const labelHeight = 28;
      
      const labelX = exhibitX - labelWidth / 2;
      const labelY = exhibitY - labelHeight / 2;
      
      // 扩大点击检测范围，增加容错
      const tolerance = 10; // 容错像素
      const clickLeft = labelX - tolerance;
      const clickTop = labelY - tolerance;
      const clickRight = labelX + labelWidth + tolerance;
      const clickBottom = labelY + labelHeight + tolerance;
      
      // 检查点击是否在区域内
      if (tapX >= clickLeft && tapX <= clickRight && 
          tapY >= clickTop && tapY <= clickBottom) {
        
        // 计算距离中心点的距离，选择最近的
        const centerX = labelX + labelWidth / 2;
        const centerY = labelY + labelHeight / 2;
        const distance = Math.sqrt(Math.pow(tapX - centerX, 2) + Math.pow(tapY - centerY, 2));
        
        if (distance < minDistance) {
          minDistance = distance;
          clickedExhibit = exhibit;
        }
      }
    });
    
    if (clickedExhibit) {
      console.log('点击了展项:', clickedExhibit.name);
      this.showExhibitContent(clickedExhibit);
    } else {
      console.log('未点击到任何展项');
    }
  },

  // 显示展项内容弹窗
  showExhibitContent(exhibit) {
    this.setData({
      showContentModal: true,
      currentExhibitContent: exhibit.content,
      currentExhibitName: exhibit.name,
      clickedExhibitId: exhibit.id
    });
  },

  // 关闭内容弹窗
  closeContentModal() {
    this.setData({
      showContentModal: false,
      currentExhibitContent: '',
      currentExhibitName: '',
      clickedExhibitId: null
    });
  },

  // 放大功能
  handleZoomIn() {
    if (!this.data.isImageLoaded) return;
    
    const newScale = Math.min(this.data.scale * 2, this.data.maxScale);
    this.setData({
      scale: newScale,
      scalePercent: Math.floor(newScale * 100)
    });
    
    this.checkBounds();
  },

  // 缩小功能
  handleZoomOut() {
    if (!this.data.isImageLoaded) return;
    
    const newScale = Math.max(this.data.scale / 2, this.data.minScale);
    this.setData({
      scale: newScale,
      scalePercent: Math.floor(newScale * 100)
    });
    
    this.checkBounds();
  },

  // 监听用户双击事件
  handleDoubleTap(e) {
    console.log(1111);
    const now = Date.now();
    if (now - this.data.lastTouchTime < 300) {
      let newScale, newOffsetX = 0, newOffsetY = 0;
      
      // 计算新的缩放比例：当前比例 * 2，但不超过4倍
      newScale = Math.min(this.data.scale * 2, 4);
      
      // 如果已经达到最大缩放（4倍），双击回到原始大小
      if (this.data.scale >= 4) {
        newScale = this.data.fitScale;
      }
      
      // 计算双击位置的偏移，使双击点保持在屏幕同一位置
      const tapX = e.detail.x - this.data.canvasWidth/2;
      const tapY = e.detail.y - this.data.canvasHeight/2;
      
      // 计算新的偏移量，使双击点保持在屏幕上的同一位置
      newOffsetX = tapX - (tapX - this.data.offsetX) * (newScale / this.data.scale);
      newOffsetY = tapY - (tapY - this.data.offsetY) * (newScale / this.data.scale);
      
      this.setData({
        scale: newScale,
        offsetX: newOffsetX,
        offsetY: newOffsetY,
        scalePercent: Math.floor(newScale * 100),
        lastTouchTime: now
      });
      
      // 边界检查
      this.checkBounds();
    } else {
      this.setData({ lastTouchTime: now });
    }
  },

  // 边界检查
  checkBounds() {
    const { scale, imageWidth, imageHeight, canvasWidth, canvasHeight } = this.data;
    
    const scaledWidth = imageWidth * scale;
    const scaledHeight = imageHeight * scale;
    
    const maxX = Math.max(0, (scaledWidth - canvasWidth) / 2);
    const maxY = Math.max(0, (scaledHeight - canvasHeight) / 2);
    
    let newOffsetX = this.data.offsetX;
    let newOffsetY = this.data.offsetY;
    
    newOffsetX = Math.max(-maxX, Math.min(newOffsetX, maxX));
    newOffsetY = Math.max(-maxY, Math.min(newOffsetY, maxY));
    
    this.setData({
      offsetX: newOffsetX,
      offsetY: newOffsetY
    });
    
    this.drawImage();
  },

  // 优化的触摸处理
  handleTouchStart(e) {
    const touches = e.touches;
    // 数量为1，单指触摸
    if (touches.length === 1) {
      this.startX = touches[0].clientX;
      this.startY = touches[0].clientY;
      this.startOffsetX = this.data.offsetX;
      this.startOffsetY = this.data.offsetY;
      
      // 重置缩放状态
      this.setData({ isScaling: false });
      
    } else if (touches.length === 2) {
      const touch1 = touches[0];
      const touch2 = touches[1];
      
      // 计算初始距离
      this.startDistance = Math.sqrt(
        Math.pow(touch2.clientX - touch1.clientX, 2) +
        Math.pow(touch2.clientY - touch1.clientY, 2)
      );
      
      // 计算双指中心点
      this.centerX = (touch1.clientX + touch2.clientX) / 2;
      this.centerY = (touch1.clientY + touch2.clientY) / 2;
      
      // 保存当前状态
      this.startScale = this.data.scale;
      this.startOffsetX = this.data.offsetX;
      this.startOffsetY = this.data.offsetY;
      
      // 计算图片上的相对位置
      this.imageCenterX = (this.centerX - this.data.canvasWidth/2 - this.startOffsetX) / this.startScale;
      this.imageCenterY = (this.centerY - this.data.canvasHeight/2 - this.startOffsetY) / this.startScale;
      
      // 设置缩放状态
      this.setData({ 
        isScaling: true,
        lastCenterX: this.centerX,
        lastCenterY: this.centerY,
        lastImageCenterX: this.imageCenterX,
        lastImageCenterY: this.imageCenterY
      });
    }
  },

  // 优化的触摸移动处理
  handleTouchMove(e) {
    const now = Date.now();
    
    // 节流处理：限制处理频率
    if (now - this.data.lastMoveTime < this.data.moveThrottleInterval) {
      return;
    }
    this.setData({ lastMoveTime: now });
    
    const touches = e.touches;
    
    if (touches.length === 1 && !this.data.isScaling) {
      // 单指移动
      const deltaX = touches[0].clientX - this.startX;
      const deltaY = touches[0].clientY - this.startY;
      
      const newOffsetX = this.startOffsetX + deltaX;
      const newOffsetY = this.startOffsetY + deltaY;
      
      this.setData({
        offsetX: newOffsetX,
        offsetY: newOffsetY
      });
      
      this.checkBounds();
      
    } else if (touches.length === 2) {
      // 双指缩放 - 使用防抖和精确计算
      const touch1 = touches[0];
      const touch2 = touches[1];
      
      // 计算当前距离
      const currentDistance = Math.sqrt(
        Math.pow(touch2.clientX - touch1.clientX, 2) +
        Math.pow(touch2.clientY - touch1.clientY, 2)
      );
      
      if (this.startDistance > 0 && currentDistance > 0) {
        const scaleRatio = currentDistance / this.startDistance;
        let newScale = this.startScale * scaleRatio;
        
        // 限制缩放范围
        newScale = Math.max(this.data.minScale, Math.min(newScale, this.data.maxScale));
        
        // 防抖处理：只有当缩放变化超过阈值时才更新
        const scaleChange = Math.abs(newScale - this.data.lastScale);
        if (scaleChange < 0.01 && this.data.isScaling) {
          return;
        }
        
        // 计算当前双指中心
        const currentCenterX = (touch1.clientX + touch2.clientX) / 2;
        const currentCenterY = (touch1.clientY + touch2.clientY) / 2;
        
        // 使用矩阵变换确保精确的位置保持
        const newOffsetX = currentCenterX - this.data.canvasWidth/2 - this.imageCenterX * newScale;
        const newOffsetY = currentCenterY - this.data.canvasHeight/2 - this.imageCenterY * newScale;
        
        this.setData({
          scale: newScale,
          offsetX: newOffsetX,
          offsetY: newOffsetY,
          scalePercent: Math.floor(newScale * 100),
          lastScale: newScale
        });
        
        this.checkBounds();
      }
    }
  },

  handleTouchEnd(e) {
    // 重置状态
    this.startDistance = 0;
    
    // 延迟重置缩放状态，避免快速切换
    setTimeout(() => {
      this.setData({ isScaling: false });
    }, 100);
  },

  // 底部篇章名点击事件
  handleChapterClick(e) {
    const chapterId = e.currentTarget.dataset.id;
    const chapterList = this.data.chapterList;  //篇章列表

    chapterList.forEach((value, index) => {
      if (value.id == chapterId) {
        //把选中的篇章下的展项赋值
        this.setData({
          exhibitList: value.children
        });
        console.log(value.children);
        this.generateExhibitPositions(value.children);
      }
    });

    this.setData({
      selectedChapter: chapterId
    });
  },

  // 语音导览点击事件
  goAudioGuide(e) {
    // 页面跳转
    wx.navigateTo({
      url: '/pages/audio_guide/audio_guide'
    })
  },


});